﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using MxWeiXinPF.DBUtility;
using MxWeiXinPF.Common;//Please add references
namespace MxWeiXinPF.DAL
{
	/// <summary>
	/// 数据访问类:wxapp_userList
	/// </summary>
	public partial class wxapp_userList
	{
		public wxapp_userList()
		{}
		#region  BasicMethod

		/// <summary>
		/// 得到最大ID
		/// </summary>
		public int GetMaxId()
		{
		return DbHelperSQL.GetMaxID("id", "wxapp_userList"); 
		}

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(int id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from wxapp_userList");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)
			};
			parameters[0].Value = id;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public int Add(MxWeiXinPF.Model.wxapp_userList model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into wxapp_userList(");
            strSql.Append("wxappId,userId,applyTime,verifyTime,verifyPerson,status,validDate,price,qrCodeUrl)");
			strSql.Append(" values (");
            strSql.Append("@wxappId,@userId,@applyTime,@verifyTime,@verifyPerson,@status,@validDate,@price,@qrCodeUrl)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@wxappId", SqlDbType.Int,4),
					new SqlParameter("@userId", SqlDbType.Int,4),
					new SqlParameter("@applyTime", SqlDbType.DateTime),
					new SqlParameter("@verifyTime", SqlDbType.DateTime),
					new SqlParameter("@verifyPerson", SqlDbType.VarChar,50),
					new SqlParameter("@status", SqlDbType.Int,4),
					new SqlParameter("@validDate", SqlDbType.DateTime),
					new SqlParameter("@price", SqlDbType.Decimal,9),
                    new SqlParameter("@qrCodeUrl", SqlDbType.VarChar,500)};
			parameters[0].Value = model.wxappId;
			parameters[1].Value = model.userId;
			parameters[2].Value = model.applyTime;
			parameters[3].Value = model.verifyTime;
			parameters[4].Value = model.verifyPerson;
			parameters[5].Value = model.status;
			parameters[6].Value = model.validDate;
			parameters[7].Value = model.price;
            parameters[8].Value = model.qrCodeUrl;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(MxWeiXinPF.Model.wxapp_userList model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update wxapp_userList set ");
			strSql.Append("wxappId=@wxappId,");
			strSql.Append("userId=@userId,");
			strSql.Append("applyTime=@applyTime,");
			strSql.Append("verifyTime=@verifyTime,");
			strSql.Append("verifyPerson=@verifyPerson,");
			strSql.Append("status=@status,");
			strSql.Append("validDate=@validDate,");
			strSql.Append("price=@price,");
            strSql.Append("qrCodeUrl=@qrCodeUrl");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@wxappId", SqlDbType.Int,4),
					new SqlParameter("@userId", SqlDbType.Int,4),
					new SqlParameter("@applyTime", SqlDbType.DateTime),
					new SqlParameter("@verifyTime", SqlDbType.DateTime),
					new SqlParameter("@verifyPerson", SqlDbType.VarChar,50),
					new SqlParameter("@status", SqlDbType.Int,4),
					new SqlParameter("@validDate", SqlDbType.DateTime),
					new SqlParameter("@price", SqlDbType.Decimal,9),
                    new SqlParameter("@qrCodeUrl", SqlDbType.VarChar,500),
					new SqlParameter("@id", SqlDbType.Int,4)};
			parameters[0].Value = model.wxappId;
			parameters[1].Value = model.userId;
			parameters[2].Value = model.applyTime;
			parameters[3].Value = model.verifyTime;
			parameters[4].Value = model.verifyPerson;
			parameters[5].Value = model.status;
			parameters[6].Value = model.validDate;
			parameters[7].Value = model.price;
            parameters[8].Value = model.qrCodeUrl;
            parameters[9].Value = model.id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from wxapp_userList ");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)
			};
			parameters[0].Value = id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string idlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from wxapp_userList ");
			strSql.Append(" where id in ("+idlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public MxWeiXinPF.Model.wxapp_userList GetModel(int id)
		{
			
			StringBuilder strSql=new StringBuilder();
            strSql.Append("select  top 1 id,wxappId,userId,applyTime,verifyTime,verifyPerson,status,validDate,price,qrCodeUrl from wxapp_userList ");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.Int,4)
			};
			parameters[0].Value = id;

			MxWeiXinPF.Model.wxapp_userList model=new MxWeiXinPF.Model.wxapp_userList();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public MxWeiXinPF.Model.wxapp_userList DataRowToModel(DataRow row)
		{
			MxWeiXinPF.Model.wxapp_userList model=new MxWeiXinPF.Model.wxapp_userList();
			if (row != null)
			{
				if(row["id"]!=null && row["id"].ToString()!="")
				{
					model.id=int.Parse(row["id"].ToString());
				}
				if(row["wxappId"]!=null && row["wxappId"].ToString()!="")
				{
					model.wxappId=int.Parse(row["wxappId"].ToString());
				}
				if(row["userId"]!=null && row["userId"].ToString()!="")
				{
					model.userId=int.Parse(row["userId"].ToString());
				}
				if(row["applyTime"]!=null && row["applyTime"].ToString()!="")
				{
					model.applyTime=DateTime.Parse(row["applyTime"].ToString());
				}
				if(row["verifyTime"]!=null && row["verifyTime"].ToString()!="")
				{
					model.verifyTime=DateTime.Parse(row["verifyTime"].ToString());
				}
				if(row["verifyPerson"]!=null)
				{
					model.verifyPerson=row["verifyPerson"].ToString();
				}
				if(row["status"]!=null && row["status"].ToString()!="")
				{
					model.status=int.Parse(row["status"].ToString());
				}
				if(row["validDate"]!=null && row["validDate"].ToString()!="")
				{
					model.validDate=DateTime.Parse(row["validDate"].ToString());
				}
				if(row["price"]!=null && row["price"].ToString()!="")
				{
					model.price=decimal.Parse(row["price"].ToString());
				}
                if (row["qrCodeUrl"] != null)
                {
                    model.qrCodeUrl = row["qrCodeUrl"].ToString();
                }


			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
            strSql.Append("select id,wxappId,userId,applyTime,verifyTime,verifyPerson,status,validDate,price,qrCodeUrl ");
			strSql.Append(" FROM wxapp_userList ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
            strSql.Append(" id,wxappId,userId,applyTime,verifyTime,verifyPerson,status,validDate,price,qrCodeUrl ");
			strSql.Append(" FROM wxapp_userList ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM wxapp_userList ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.id desc");
			}
			strSql.Append(")AS Row, T.*  from wxapp_userList T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "wxapp_userList";
			parameters[1].Value = "id";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod


        public bool Exists(int wxappId, int userId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from wxapp_userList");
            strSql.Append(" where wxappId=@wxappId and userId=@userId");
            SqlParameter[] parameters = {
					new SqlParameter("@wxappId", SqlDbType.Int,4),
                    	new SqlParameter("@userId", SqlDbType.Int,4)
			};
            parameters[0].Value = wxappId;
            parameters[1].Value = userId;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public MxWeiXinPF.Model.wxapp_userList GetModel(int wxappId, int userId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 id,wxappId,userId,applyTime,verifyTime,verifyPerson,status,validDate,price,qrCodeUrl from wxapp_userList ");
            strSql.Append(" where wxappId=@wxappId and userId=@userId ");
            SqlParameter[] parameters = {
					new SqlParameter("@wxappId", SqlDbType.Int,4),
                    new SqlParameter("@userId", SqlDbType.Int,4)
			};
            parameters[0].Value = wxappId;
            parameters[0].Value = userId;

            MxWeiXinPF.Model.wxapp_userList model = new MxWeiXinPF.Model.wxapp_userList();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

     
        /// <summary>
        /// 查看用户购买该小程序的信息
        /// </summary>
        /// <param name="wxappId">小程序表主键</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public DataTable GetModelByWxappIdAndUserId(int wxappId, int userId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select '' status_s,app.*,u.validDate usedvalidDate,u.status  usedStatus,u.validDate,u.applyTime,u.verifyTime,u.verifyPerson,u.userId,u.wxappId,u.price uprice,u.qrCodeUrl
 from wxapp_appinfo app right join wxapp_userList u on app.id=u.wxappId where  app.status=1 and u.userId=@userId and u.wxappId=@wxappId");
            SqlParameter[] parameters = {
					new SqlParameter("@userId", SqlDbType.Int,4),
                    new SqlParameter("@wxappId", SqlDbType.Int,4)
			};
            parameters[0].Value = userId;
            parameters[1].Value = wxappId;

            MxWeiXinPF.Model.wxapp_userList model = new MxWeiXinPF.Model.wxapp_userList();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds!=null && ds.Tables.Count>0)
            {
                return   ds.Tables[0] ;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 用户购买app的信息列表【分页】
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataSet GetModelByUserApp(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT '' as status_s,'' buyinfo,'' caozuo, a.*,u.id AS auid,u.applyTime,u.verifyTime,u.verifyPerson,u.status AS austatus,u.validDate AS auvalidDate,u.price AS auprice,u.qrCodeUrl AS auqrCodeUrl, 
m.user_name,m.storeName, m.storeCompanyId,buy.buyCount
 FROM dbo.wxapp_userList u  LEFT JOIN dbo.wxapp_appinfo a ON u.wxappId=a.id LEFT JOIN dbo.dt_manager m ON u.userId=m.id LEFT JOIN 
( SELECT userid,wxappId,count(1) AS buyCount FROM wxapp_buyOrders WHERE status=1 GROUP BY userId,wxappId) AS buy ON u.userId=buy.userId and buy.wxappId=a.id
   
   ");
            if (strWhere.Trim() != "")
            {
                strSql.Append("  WHERE a.status=1  " + strWhere);
            }
            recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
            return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        }

        /// <summary>
        /// 通过userlist表的id获取该条用户小程序的具体信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataSet GetTotModel(int id)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT '' as status_s,'' buyinfo,'' caozuo, a.*,u.id AS auid,u.applyTime,u.verifyTime,u.verifyPerson,u.status AS austatus,u.validDate AS auvalidDate,u.price AS auprice,u.qrCodeUrl AS auqrCodeUrl, 
m.user_name,m.storeName, m.storeCompanyId,buy.buyCount
 FROM dbo.wxapp_userList u  LEFT JOIN dbo.wxapp_appinfo a ON u.wxappId=a.id LEFT JOIN dbo.dt_manager m ON u.userId=m.id LEFT JOIN 
( SELECT userid,wxappId,count(1) AS buyCount FROM wxapp_buyOrders WHERE status=1 GROUP BY userId,wxappId) AS buy ON u.userId=buy.userId  and buy.wxappId=a.id
   
   ");
            
                strSql.Append("  WHERE  u.id="+id);

                return DbHelperSQL.Query(strSql.ToString());
        }


		#endregion  ExtensionMethod
	}
}

